from django import forms
from django.contrib.auth import get_user_model
from django.core.cache import cache

from apps.BaseForm import FormMixin


class LoginForm(forms.Form, FormMixin):
    account = forms.CharField(required=True,
                              min_length=2,
                              max_length=20,
                              error_messages={
                                  "required": "账号必填~~",
                                  "min_length": "账号长度 2 ~ 20 个字符~~",
                                  "max_length": "账号长度 2 ~ 20 个字符~~",
                              })

    password = forms.CharField(required=True,
                               error_messages={
                                   "required": "账号必填~~",
                               })

    img_captcha = forms.CharField(required=True,
                                  error_messages={
                                      "required": "账号必填~~",
                                  })

    def clean_img_captcha(self):
        img_captcha = self.cleaned_data.get('img_captcha')
        if (not img_captcha) or img_captcha.lower() != cache.get(f'img_captcha_{img_captcha.lower()}'):
            raise forms.ValidationError('图形验证码错误, 请重新填写~~')

    def clean_account(self):
        account = self.cleaned_data.get('account')
        user = get_user_model().objects.filter(account=account)
        if not user.exists():
            raise forms.ValidationError("账号或密码错误~~")
        return account
